$(function(){
    $.fn.extend({
        pagenation:function(options){
            var _default = {data:'load_data',form:'pageForm',callback:$.noop};
            var pageSize = 'pageSize';
            var totalPage = 'totalPage';
            var currentPage = 'currentPage';
            var totalCount = 'totalCount';
            var showPages = 5;//最多展示5个分页按钮
            //初始化个分页情况为4,0,1,在变动过程中，会出现1,3,1或者1,0,4
            var pre = 4;
            var middle = 0;
            var last = 1;
            var prevTxt = '上一页';
            var nextTxt = '下一页';
            var ellipse = '....';
            return this.each(function(){
                var opt = $.extend(_default,options);
                var $this = $(this);        
                createPagenation($this,opt);
                return $this;
            });

            function createPagenation($this,opt){
                var $body = $($this.children()[1]);
                var $form = $('#'+opt.form); 
                var $page = $this.children().last();
                var _pageSize = parseInt($('#'+pageSize).val());
                var _totalPage = parseInt($('#'+totalPage).val());
                var _curPage = parseInt($('#'+currentPage).val());
                var _totalCount = parseInt($('#'+totalCount).val());
                var $pagec = $($page.find('tr td')[0]);
                $pagec.attr('data-form',opt.form);
                $pagec.attr('data-curpage',_curPage);
                $pagec.attr('load-data',opt.data);
                $pagec[0].callback = opt.callback;
                renderTrs($body);
                $pagec.empty();
                createItems($pagec,_totalPage,_pageSize,_curPage);
                createTotalInfo($pagec,_totalPage,_totalCount);
            }
            function renderTrs($body){
                var trs = $body.children('tr');
                trs.each(function(){
                    $(this).bind('mouseover',function(){
                        $(this).addClass('hover');    
                    }).bind('mouseout',function(){
                        $(this).removeClass('hover');    
                    });           
                });
            }
            function createItems($pagec,totalPage,pageSize,curPage){
                createPrevItem($pagec,totalPage,curPage);
                
                var _pre = pre;
                var _middle = middle;
                var _last = last;
                if( totalPage == 0 ){
                    createNextItem($pagec,totalPage,curPage);
                    return;
                }
                if( totalPage <= 4 ){
                    _pre = totalPage;
                    createPreItem($pagec,_pre,curPage);
                    createNextItem($pagec,totalPage,curPage);
                    return;
                }
                if( totalPage > showPages && curPage >= showPages && curPage <= totalPage-pre ){
                    _pre = 1;
                    _middle = 3;
                    _last = 1;
                }
                if(totalPage > showPages && curPage > totalPage - pre && curPage <= totalPage){
                    _pre = 1;
                    _middle = 0;
                    _last = 4;
                }
                createPreItem($pagec,_pre,curPage);
                if( totalPage > showPages ){
                    createMiddleItem($pagec,_middle,curPage);
                    createLastItem($pagec,_last,totalPage,curPage);
                }else if(totalPage == showPages){
                    createItem($pagec,totalPage,curPage);
                }
                createNextItem($pagec,totalPage,curPage);
            }

            function createPreItem($pagec,pre,curPage){
                for( var i = 0 ; i < pre ; i++){
                    var $item = createItem($pagec,i+1,curPage);
                    if( i+1 == curPage ) {
                        $item.addClass('active');
                    }
                }
            }
            function createMiddleItem($pagec,middle,curPage){
                if( middle > 0 ){
                    createElliItem($pagec);
                    for( var i = curPage - 2 ; i < curPage + 1 ; i++){
                        var $item = createItem($pagec,i+1,curPage);
                        if( i+1 == curPage ) {
                            $item.addClass('active');
                        }
                    }
                }
                
            }
            function createLastItem($pagec,last,totalPage,curPage){
                if( last > 0 ){
                    createElliItem($pagec);
                    for( var i = totalPage-last ; i < totalPage ; i++){
                        var $item = createItem($pagec,i+1,curPage);
                        if( i+1 == curPage ) {
                            $item.addClass('active');
                        }
                    }
                }
                
            }
            function createItem($pagec,index,curPage){
                var $item = $('<a href="javascript:void(0);"></a>');
                $pagec.append($item);
                $item.text(index);
                if( curPage != index ){
                    $item.bind('click',itemClickHandler);
                    $item.bind('mouseover',itemMouseoveHandler);
                    $item.bind('mouseout',itemMouseoutHandler);
                }
                return $item;
            }
            function createElliItem($pagec){
                var $item = $('<a href="javascript:void(0);"></a>');
                $pagec.append($item);
                $item.html(ellipse);
                $item.addClass('elli');
                return $item;
            }
            function createPrevItem($pagec,totalPage,curPage){
                var $prevItem = $('<a href="javascript:void(0);"></a>');
                $pagec.append($prevItem);
                $prevItem.addClass('page-btn');
                $prevItem.html(prevTxt);
                if( curPage == 1 ) {
                    $prevItem.addClass('disabled');
                    return ;
                }
                $prevItem.bind('click',prevClickHandler);
                $prevItem.bind('mouseover',btnMouseoveHandler);
                $prevItem.bind('mouseout',btnMouseoutHandler);
            }
            function createNextItem($pagec,totalPage,curPage){
                var $nextItem = $('<a href="javascript:void(0);"></a>');
                $pagec.append($nextItem);
                $nextItem.addClass('page-btn');
                $nextItem.html(nextTxt);
                if( curPage == totalPage || totalPage == 0 ) {
                    $nextItem.addClass('disabled');
                    return ;
                }
                $nextItem.bind('click',nextClickHandler);
                $nextItem.bind('mouseover',btnMouseoveHandler);
                $nextItem.bind('mouseout',btnMouseoutHandler);
            }

            function btnMouseoveHandler(){
                $(this).addClass('btn-hover');
            }
            function btnMouseoutHandler(){
                $(this).removeClass('btn-hover');
            }
            function itemMouseoveHandler(){
                $(this).addClass('hover');
            }
            function itemMouseoutHandler(){
                $(this).removeClass('hover');
            }
            function prevClickHandler(e){
                var curPage = parseInt($(this).parent().attr('data-curpage'));
                curPage = curPage == 1 ? 1 : curPage -1;
                $('#'+currentPage).val(curPage);
                $(this).parent().attr('data-curpage',curPage);
                clickHandler.apply(this,[e]);
            }
            function nextClickHandler(e){
                var curPage = parseInt($(this).parent().attr('data-curpage'));
                var totalPage = $('#'+totalPage).val();
                curPage = curPage == totalPage ? curPage:curPage + 1;
                $('#'+currentPage).val(curPage);
                $(this).parent().attr('data-curpage',curPage);
                clickHandler.apply(this,[e]);
            }
            function itemClickHandler(e){
                var curPage = $(this).text();
                $(this).parent().attr('data-curpage',curPage);
                $('#'+currentPage).val(curPage);
                clickHandler.apply(this,[e]);
            }
            function clickHandler(e){
                var $pagec = $(this).parent();
                var $form = $('#'+$pagec.attr('data-form'));
                var data = $form.serialize();
                var url =  $form.attr("action");
                var $datac = $form.parent();
                var $head = $datac.prev();
                var cols = $($head.children('tr')[0]).children().length;
                var $c = $form.parent().parent();
                $.ajax({
                    type:'get',
                    dataType:'html',
                    url:url+'?'+data+'&t='+new Date().getTime(),
                    contentType:"application/x-www-form-urlencoded;charset=utf-8",
                    beforeSend:function(){
                        $datac.html('<tr><td colspan="'+cols+'"><div class="u-table-loading"></div></td></tr>');
                    },
                    success:function(result){
                        $datac.html(result);
                        var callback = $pagec[0].callback;
                        var opt = {data:$pagec.attr('load-data'),form:$pagec.attr('data-form'),callback:callback};
                        createPagenation($c,opt);
                        callback();
                    },
                    error:function(e){
                        throw '异步加载表格数据有误 :'+e.status+','+e.statusText;
                    },
                    complete:function(){
                        //$($datac.find('.u-table-loading')[0]).parent().parent().remove();
                    }

                });
            }
            function createTotalInfo($pagec,totalPage,totalCount){
                var $info = $('<span>共<span >'+totalPage+'</span>页&nbsp;&nbsp;<span>'+totalCount+'</span>条记录</span>');
                $pagec.append($info);
            }
            
        }    
    });      
});
